import {staticResourceContainer} from "../containers/staticResourceContainer"
import * as path from "path"
import * as fs from "fs"

export class StaticResourceManager {
  static mapping = staticResourceContainer
  private static workdir = ""

  private static setWorkDir(workdir: string) {
    StaticResourceManager.workdir = workdir
  }
  constructor(workdir: string) {
    StaticResourceManager.setWorkDir(workdir)
  }

  static isStaticResource = (req: HttpRequest) => {
    const staticPaths = Object.keys(StaticResourceManager.mapping)
    return staticPaths.some(key => req.url.startsWith(key))
  }

  static getStaticResource = (fileName: string): string| null => {
    const staticDirsArr = Object.values(StaticResourceManager.mapping)
    const staticDir = staticDirsArr.reduce((prev, current) => {
      return prev.concat(current)
    }, [])
    fileName = fileName.startsWith("/") ? fileName.slice(1) : fileName
    const fileArr = fileName.split("/")
    const allPossiblePath = staticDir.map(dir => path.resolve(StaticResourceManager.workdir, dir, ...fileArr))
    let filePath = null
    allPossiblePath.some(file => {
      if (fs.existsSync(file)) {
        filePath = file
        return true
      }
    })
    return filePath
  }
}
